package com.uw.uwrpc.core.config;

import com.uw.uwrpc.core.api.Filter;
import com.uw.uwrpc.core.api.LoadBalancer;
import com.uw.uwrpc.core.api.RegistryCenter;
import com.uw.uwrpc.core.api.Router;
import com.uw.uwrpc.core.cluster.loadbalancer.RoundRobinLoadBalancer;
import com.uw.uwrpc.core.cluster.router.GrayRouter;
import com.uw.uwrpc.core.consumer.ConsumerBootstrap;
import com.uw.uwrpc.core.consumer.ConsumerInvoker;
import com.uw.uwrpc.core.consumer.invoker.HttpConsumerInvoker;
import com.uw.uwrpc.core.filter.ContextParamFilter;
import com.uw.uwrpc.core.meta.InstanceMeta;
import com.uw.uwrpc.core.registry.impl.UWRegistryCenter;
import com.uw.uwrpc.core.registry.impl.ZookeeperRegistryCenter;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@SpringBootConfiguration
@EnableConfigurationProperties({UWRpcProperty.class, UWRegistryProperty.class})
public class ConsumerConfig {
    @Bean
    public ConsumerBootstrap consumerBootstrap() {
        return new ConsumerBootstrap();
    }

    @Bean
    public LoadBalancer<InstanceMeta> loadBalancer() {
        return new RoundRobinLoadBalancer();
        //return LoadBalancer.DEFAULT;
    }

    @Bean
    public Router<InstanceMeta> router(ConsumerBootstrap consumerBootstrap) {
        return new GrayRouter(consumerBootstrap.getUwRpcProperty().getConsumer().getGrayRatio());
    }

    @Bean
    public ConsumerInvoker consumerInvoker(UWRpcProperty uwRpcProperty) {
        return new HttpConsumerInvoker(uwRpcProperty.getConsumer().getReadTimeout()
                , uwRpcProperty.getConsumer().getWriteTimeout()
                , uwRpcProperty.getConsumer().getConnectTimeout());
    }

    @Bean
    @ConditionalOnMissingBean
    public ApolloChangedListener consumer_apolloChangedListener() {
        return new ApolloChangedListener();
    }


    @Bean
    public RegistryCenter registerCenter(UWRegistryProperty uwRegistryProperty) {
        return new UWRegistryCenter(uwRegistryProperty);
    }

    //@Bean
    //public Interceptor cacheInterceptor() {
    //    return new CacheInterceptor();
    //}
    //@Bean
    //public Interceptor mockInterceptor() {
    //    return new MockInterceptor();
    //}

    @Bean
    public Filter contextParamFilter() {
        return new ContextParamFilter();
    }
}
